#include "Win32Frame.h"
#include "MsgMethod.h"

// Global variable & method
//-----------------------------------------------------------------------------------------------------------------------------------------
extern HWND g_hWnd;
extern void _PrintMessage(const TCHAR* szComment, HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam);
//=========================================================================================================================================

LRESULT CALLBACK _WndProc(HWND hWnd, UINT nMessage, WPARAM wParam, LPARAM lParam)
{
	for (int ii = 0; ii < sizeof(MsgMapTable) / sizeof(*MsgMapTable); ii++)
	{
		if (nMessage == MsgMapTable[ii].nMessage)
		{
			MsgMapTable[ii].MsgProc(hWnd, wParam, lParam);
			break;
		}
	}

	_PrintMessage(_T("WndProcess"), hWnd, nMessage, wParam, lParam);

	return DefWindowProc(hWnd, nMessage, wParam, lParam);
}

bool RegisterWndClass(HINSTANCE hInstance, const TCHAR* szClsName)
{
	ATOM lRes	= 0;
	if (NULL != szClsName && NULL != *szClsName)
	{
		WNDCLASS wc			= {0};
		wc.hInstance		= hInstance;
		wc.lpszClassName	= szClsName;
		wc.lpfnWndProc		= _WndProc;
		wc.hbrBackground	= (HBRUSH)GetStockObject(WHITE_BRUSH);
		wc.style			= CS_HREDRAW|CS_VREDRAW;
		wc.lpszMenuName		= NULL;
		wc.hIcon			= (HICON)LoadIcon(NULL, MAKEINTRESOURCE(IDI_APPLICATION));
		wc.hCursor			= (HCURSOR)LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW));
		lRes = ::RegisterClass(&wc);
		assert(0 != lRes);
	}

	return (0 != lRes);
}

HWND CreateWnd(HINSTANCE hInstance, const TCHAR* szClsName, const TCHAR* szCaption, 
			   DWORD dwStyle, int nX, int nY, int nWidth, int nHight)
{
	assert(NULL != szClsName && NULL != szCaption);

	HWND	hWnd	= NULL;
	if (NULL != szClsName)
	{
		hWnd	=  CreateWindow(szClsName, szCaption, dwStyle, nX, nY, nWidth, nHight, NULL, NULL, hInstance, NULL);
		assert(NULL != hWnd && IsWindow(hWnd));
	}

	return hWnd;
}

void ShowWnd(HWND hWnd)
{
	ShowWindow(hWnd, SW_SHOW);
	UpdateWindow(hWnd);

	return;
}

void RunMessageLoop()
{
	MSG Msg;
	
	while (true)
	{
		if (PeekMessage(&Msg, (HWND)NULL, 0, 0, PM_REMOVE))
		{
			_PrintMessage(_T("PeekMessage"), Msg.hwnd, Msg.message, Msg.wParam, Msg.lParam);

			TranslateMessage(&Msg);
		
			_PrintMessage(_T("Translate"), Msg.hwnd, Msg.message, Msg.wParam, Msg.lParam);
			
			DispatchMessage(&Msg);

			_PrintMessage(_T("Dispatch"), Msg.hwnd, Msg.message, Msg.wParam, Msg.lParam);

			if (Msg.message == WM_QUIT)
			{
				break;
			}	
		}
	}

	return;
}